package com.redhat.auth.il18n;


import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.components.UIBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opensymphony.xwork2.util.ValueStack;

public class Tag18n extends UIBean {
	
	private String key;
	
	private String path;
	
	private String locale;
	
	private static Logger logger = LoggerFactory
	.getLogger(Tag18n.class);
	
	public Tag18n(ValueStack stack, HttpServletRequest request,
			HttpServletResponse response) {
		super(stack, request, response);
		if(locale==null)locale = request.getLocale().toString();
		if(path==null) path="common";
	}

	@Override
	protected String getDefaultTemplate() {
		return "lps_i18n";
	}
	
	@Override
	public String getTheme() {
		return "redwork";
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
	
	@Override
	protected void evaluateExtraParams() {
		super.evaluateExtraParams();
		String path = "i18n/"+getLocale()+"/"+getPath();
		String keyValue = null;
		ResourceBundle resource = null;
		//读取resources
		try {
		   resource = ResourceBundle.getBundle(path);
		   keyValue = resource.getString(key);
		}catch(MissingResourceException e){
			keyValue = defaultConv(key);
			//不提示英文，只提示中文
			if(!getLocale().equals("en"))
		    logger.info("I18n warn,can not find key:"+key+"-->"+keyValue);
		}
		addParameter("keyValue", keyValue.trim());
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getLocale() {
		//从session中取国际化值
		locale  = (String)request.getSession().getAttribute("IL18N-LANGUAGE");
		//从cookies中取国际化值
		if(locale==null || "".equals(locale)) locale = getCookieLanguage(request);
		//cookies中取不到，取浏览器的值
		if(locale==null || "".equals(locale)) {
			locale = request.getLocale().getLanguage()+"_"+request.getLocale().getCountry();
		}
		return locale;
	}

	public void setLocale(String locale) {
		this.locale = locale;
	}
	/**
	 * 自动转换，将英文key中的下划线及中划线转换为空格
	 * @param key
	 * @return
	 */
	private String defaultConv(String key){
		key = key.replace("_", " ");
		key = key.replace("-", " ");
		return key;
	}
	
	/**
	 * 获取cookie中的国际化语言设置
	 * @param request
	 * @return
	 */
	private String getCookieLanguage(HttpServletRequest request){
		Cookie[] cookies= request.getCookies();
		if(cookies==null)return null;
		for(int i=0;i<cookies.length;i++){
			Cookie cookie =  cookies[i];
			if(cookie.getName().equals("IL18N-LANGUAGE")){
				return cookie.getValue();
			}
		}
		return null;
	}
}
